/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.querydsl.types;

import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import com.querydsl.sql.types.AbstractType;

/**
 * 
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 */
public class BlobByteArrayType extends AbstractType<byte[]> {

    public BlobByteArrayType() {
        super(Types.BLOB);
    }

    @Override
    public Class<byte[]> getReturnedClass() {
        return byte[].class;
    }
    @Override
    public byte[] getValue(ResultSet rs, int startIndex) throws SQLException {
        Blob blob = rs.getBlob(startIndex);
        if (blob == null) {
            return null;
        }
        return blob.getBytes(1, (int)blob.length());
    }

    @Override
    public void setValue(PreparedStatement st, int startIndex, byte[] value) throws SQLException {
        if (value == null) {
            st.setBlob(startIndex, (Blob) null);
        } else {
            Blob blob = st.getConnection().createBlob();
            blob.setBytes(1, value);
            st.setBlob(startIndex, blob);
        }
    }

}
